package com.bianmaba.spring.security.basic.authentication;

import com.bianmaba.spring.security.util.ResponseUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: bianmaba-web-framework-extends
 * @description:
 * @author: Chenjiabin
 * @create: 2018-04-22 20:29
 **/
public class BianmabaAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
    /**
     * @param loginFormUrl URL where the login page can be found. Should either be
     *                     relative to the web-app context path (include a leading {@code /}) or an absolute
     *                     URL.
     */
    public BianmabaAuthenticationEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String requestType = request.getHeader("request_type");
        if ("ajax".equals(requestType)) {
            Map<String, Object> result = new HashMap<String, Object>(0);
            result.put("success", false);
            result.put("status", 401.1);
            result.put("statusText", "Not logon");
            result.put("SecurityMessage", true);
            result.put("result", "请求的资源需要用户登录后才能访问，请登录后重试！");
            ResponseUtil.writeJson(response, result, 401);
        } else {
            super.commence(request, response, authException);
        }
    }
}
